#pragma once

#include "log.hpp"
#include <iostream>
#include <string>
#include <cstring>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <functional>
#include "protocol.hpp"
enum{
    SOCKERROR = 1,
    BINDERROR,
    LISTENERROR
};

typedef std::function<void(const Request&,Response& )> func_t;

class tcpServer{
public:
    tcpServer(const uint16_t& port,func_t func) :_listen_sock(-1),_port(port),_func(func)
    {}

    void initServer(){
        //创建套接字
        _listen_sock = socket(AF_INET,SOCK_STREAM,0);
        if(_listen_sock == -1){
            logmessage(FATAL,"socket filed!");
            exit(SOCKERROR);
        }else logmessage(NORMAL,"socket success");
        //bind
        sockaddr_in local;
        socklen_t len = sizeof local;
        memset(&local,0,len);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = htonl(INADDR_ANY);
        local.sin_port = htons(_port);
        if(bind(_listen_sock,(sockaddr*)&local,len) == -1){
            logmessage(FATAL,"bind filed!");
            exit(BINDERROR);
        }
        logmessage(NORMAL,"bind succuss");
        //将sock设置为监听
        if(listen(_listen_sock,5) == -1){
            logmessage(FATAL,"listen filed!");
            exit(LISTENERROR);
        }
        logmessage(NORMAL,"listen succuss");
    }
    
    void HttpCommunication(int sockfd,func_t func){
        //1.收到一个完整的报文
    #define MAXCAP 4096
        char buffer[MAXCAP];
        ssize_t s = recv(sockfd,buffer,MAXCAP-1,0); //假设已经收到完整的报文
    
        if(s >0){
            buffer[s] = 0;
            // std::cout<<"-----------start------------"<<std::endl;
            // std::cout<<buffer<<std::endl;
            // std::cout<<"-----------end------------"<<std::endl;
            Request req(buffer);
            req.parse();
            Response res;
            func(req,res);
            send(sockfd,res.alldata.c_str(),res.alldata.size(),0);
        
        }
   
        //2.序列化
        
        //3.处理

        //4.反序列化

        //5.发送报文

    }

    void start(){
        for( ; ; ){
            //建立链接
            sockaddr_in remote;
            socklen_t len = sizeof remote;
            memset(&remote,0,len);
            int commfd = accept(_listen_sock,(sockaddr*)&remote,&len);
            if(commfd == -1){
                logmessage(ERROR,"accept filed!");
                continue;
            }
            logmessage(NORMAL,"accept succuss,sockfd:%d",commfd);
          
            pid_t id = fork();
            if(id == 0){
                close(_listen_sock);
                if(fork()!= 0)  exit(0);
                //TODO
                HttpCommunication(commfd,_func);
                close(commfd);
                exit(0);
            }
            //关闭通信接口
            close(commfd); //父进程已经不需要通信，孙子进程已经继承了通信接口了
            pid_t ret = waitpid(id,nullptr,0);
            std::cout<<"wait succuss:"<<ret<<std::endl;
        }
    }

    ~tcpServer(){
        close(_listen_sock);
    }

private:
    int _listen_sock;
    uint16_t _port;
    func_t _func;
};